package algorithm.offer;

public class OfferNum22 {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.setNext(new ListNode(2))
                .setNext(new ListNode(3))
                .setNext(new ListNode(4))
                .setNext(new ListNode(5))
                .setNext(new ListNode(6))
                .setNext(new ListNode(7));
        System.out.println(head);
        System.out.println(getKthFromEnd(head, 3));
    }
    public static ListNode getKthFromEnd(ListNode head, int k) {
        if (head == null || k <= 0) {
            return null;
        }
        ListNode slow = head, fast = head;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        while (fast != null) {
            fast = fast.next;
            slow = slow.next;
        }
        return slow;
    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }
        public ListNode setNext(ListNode next) {
            this.next = next;
            return next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }
}
